#!/usr/bin/env bash
# php

if [[ -z "${c_php_ins}" ]]; then
    f_info 'php: not install';
    echo > "${DIR}/conf/.exec-fpm" || f_fail 'php: .exec-fpm';
    echo > /dev/null;  return;
fi;
f_wait "php: install, ${c_php_ins}";  lst='';

fpm='[www4www]
user = www
group = www
;listen = 127.0.0.1:90{VER}
listen = /home/www/sock/www.fpm{VER}.sock
listen.owner = www
listen.group = www
listen.mode = 0600
pm = dynamic
pm.max_children = 50
pm.start_servers = 1
pm.min_spare_servers = 1
pm.max_spare_servers = 2
';

for v in ${c_php_ins}; do
    # install
    lst="${lst} php${v}-fpm";  x="${v/./}";
    ins="php${v}-fpm";  f_wait "php: v${v}";
    [[ -n "${c_httpd}" ]] && ins="libapache2-mod-php${v} ${ins}";
    for m in ${c_php_mod}; do ins="${ins} php${v}-${m}"; done;
    f_inst 'php' "${ins}";  tar="${DIR}/conf/php${v}";
    raw="/etc/php/${v}";  f_bkup "${raw}/fpm/php-fpm.conf";
    f_bkup "${raw}/fpm/php.ini";  f_bkup "${raw}/cli/php.ini";
    mkdir -p "${tar}" || f_fail "php: v${v} mkdir conf";
    # config: fpm.conf
    if [[ ! -f "${tar}/_fpm.conf" ]]; then
        echo "${fpm//\{VER\}/$x}" > "${tar}/_fpm.conf" \
            || f_fail "php: v${v} fpm.conf";
    fi;
    f_link "${tar}/_fpm.conf" "${raw}/fpm/php-fpm.conf";

    # config: fpm.ini
    if [[ ! -f "${tar}/fpm.ini" ]]; then
        cat "${raw}/fpm/php.ini.backup" | grep -vE '^(;|$)' \
            > "${tar}/fpm.ini" || f_fail "php: v${v} fpm.ini";
    fi;
    f_link "${tar}/fpm.ini" "${raw}/fpm/php.ini";
    # config: cli.ini
    if [[ ! -f "${tar}/cli.ini" ]]; then
        cat "${raw}/cli/php.ini.backup" | grep -vE '^(;|$)' \
            > "${tar}/cli.ini" || f_fail "php: v${v} cli.ini";
    fi;
    f_link "${tar}/cli.ini" "${raw}/cli/php.ini";
    # service
    cus="${DIR}/serv/php${v}-fpm.service";
    srv="/usr/lib/systemd/system/php${v}-fpm.service";
    [[ ! -f "${cus}" ]] && f_copy "${srv}" "${cus}";
    f_bkup "${srv}";  f_link "${cus}" "${srv}";
    f_auto "php${v}-fpm" "php${v}-fpm" 1;
    systemctl restart "php${v}-fpm" || f_fail "php: v${v} restart";
done;

echo "${lst}" > "${DIR}/conf/.exec-fpm" || f_fail 'php: create .exec-fpm';

# default
f_link "php${c_php_bin}" '/usr/bin/php';
f_link "phar${c_php_bin}.phar" '/usr/bin/phar';
f_link "phar${c_php_bin}.phar" '/usr/bin/phar.phar';

echo > /dev/null;  return;
